package com.nd.rj.common.login.communication;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;

import com.common.android.utils.httpRequest.OapHttpRequest;
import com.nd.rj.common.R;
import com.nd.rj.common.login.GlobalSetting;
import com.nd.rj.common.login.entity.ClientInfo;

/**
 * uap同步类
 * 
 * @author yiyang
 * 
 */
public class OapCom {
    
    private static String OAP_URL_OUT = "http://oap.99.com/";
    private static String OAP_URL_IN = "http://192.168.94.21/oap21/";
    // 请求地址定义
    private final String LOGIN_URL = "passport/login";
    private final String DEPT_URL = "unit/depts";

    private final String USERDETAIL_URL = "user/info";
    private final String BINDUSER_URL = "user/list";
    private final String CHANGEUSER_URL = "passport/changeuser";
    private final String USERBIND_URL = "org/userbind";
    private final String USERBINDCANCEL_URL = "org/userbindcancel";
    private final String LOGIN_URL_COOKIE="passport/cookielogin";
    private final String LOGIN_URL_TICKET="passport/loginticket";
    private static OapCom mCom;

    private OapHttpRequest mHttpRequest;
    private Context mContext;
    private String mAppid;
    private OapCom(Context ctx) {
        mHttpRequest = OapHttpRequest.getInstance(ctx);
        mContext=ctx;
        mAppid=GlobalSetting.getInstance(ctx).getAppid();
    }

    public static OapCom getInstance(Context ctx) {
        if (mCom == null)
            mCom = new OapCom(ctx);
        return mCom;
    }

    /**
     * oap请求地址
     * 
     * @return 根据全局变量返回基础地址
     */
    public String getBaseUrl() {
    	int env=GlobalSetting.getInstance(mContext).getNetworkEnv();
    	if (env == GlobalSetting.NETWORK_IN) {
    		return OAP_URL_IN;
    	} else if (env == GlobalSetting.NETWORK_OUT) {
    		return OAP_URL_OUT;
    	} else { 
    		return OAP_URL_OUT;
    	}
    }

    /**
     * 用户登录
     * 
     * @param username
     * @param password
     * @return srecive
     * @return
     */
    public int userLogin( String username, String password, long unitid, long uid,
            StringBuilder receive) {
        int ireturn = R.string.nd_oap_login_error;
        // 连接oap通讯
        JSONObject json = new JSONObject();
        try {
            json.put("password", password);
            json.put("account", username);
            if (unitid > 0) {
                json.put("unitid", unitid);
                json.put("uid", uid);
            }
            if (!TextUtils.isEmpty(mAppid)){
                json.put("appid", mAppid);
            }
            // 是否启用rsa加密，可选值0|1，默认为0不启用；当值为1时，password值要设置为base64_encode(rsa_encode(password))
            json.put("rsa", "1");
            json.put("platform", "30");//平台
            String HttpUrl = getBaseUrl();
            HttpUrl += LOGIN_URL;
            ireturn = mHttpRequest.doPost(HttpUrl, json, receive);
            if (ireturn != HttpStatus.SC_OK) {
                switch (ireturn) {
                case HttpStatus.SC_BAD_REQUEST:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_limit;
                    break;
                case HttpStatus.SC_FORBIDDEN:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_psw_error;
                    break;
                case HttpStatus.SC_NOT_FOUND:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_account_not_exists;
                    break;
                default:
                    _getResponseErrMsg(receive);
                    break;
                }
            } else
                ireturn = 0;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            ireturn = R.string.nd_json_error;
        } finally {
            json = null;
        }
        return ireturn;
    }

    /**
     * 获取用户基本信息
     * 
     * @param receive
     * @param oap_uid
     * @return
     */
    public int getUserDetail(long oap_uid, String sid, StringBuilder receive) {
        int ireturn = 0;
        try {
            StringBuilder url = new StringBuilder();
            url.append(getBaseUrl()).append(USERDETAIL_URL);
            url.append("?uid=").append(oap_uid);
            mHttpRequest.setSid(sid);
            ireturn = mHttpRequest.doGet(url.toString(), receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ireturn;
    }

    /**
     * 获取部门列表
     * 
     * @param recive
     * @param unitid
     *            选填/和depitid二必须选一，单位ID（8位整数）
     * @param deptid
     *            选填/和unitid二必须选一，部门ID，为空或0表示搜索一级部门（8位整数）
     * @param issub
     *            选填是否返回子部门及下级部门，默认0 0=不返回子部门及下级部门 1=返回子部门下级部门（3位整数）
     * @return
     */
    public int getDepts(StringBuilder receive, long unitid, long deptid, int issub, String sid) {
        int ireturn = 0;
        try {
            StringBuilder url = new StringBuilder();
            url.append(getBaseUrl()).append(DEPT_URL);

            if (unitid > 0)
                url.append("?unitid=").append(unitid);
            else
                url.append("&deptid=").append(deptid);
            url.append("&issub=").append(issub);
            mHttpRequest.setSid(sid);
            ireturn = mHttpRequest.doGet(url.toString(), receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ireturn;
    }

    /**
     * 切换身份
     * 
     * @param unitid
     * @param oap_uid
     * @param recive
     * @return
     */
    public int changeUser(long unitid, long oap_uid, String sid, StringBuilder receive) {
        int ireturn = 0;
        JSONObject json = new JSONObject();
        try {
            json.put("unitid", unitid);
            json.put("uid", oap_uid);
            StringBuilder HttpUrl = new StringBuilder();
            HttpUrl.append(getBaseUrl()).append(CHANGEUSER_URL);
            mHttpRequest.setSid(sid);
            ireturn = mHttpRequest.doPost(HttpUrl.toString(), json, receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ireturn;
    }

    /**
     * 查询绑定身份信息列表
     * 
     * @param recive
     * @return
     */
    public int getBindUser(String sid, StringBuilder recive) {
        int ireturn = 0;
        try {
            StringBuilder HttpUrl = new StringBuilder();
            HttpUrl.append(getBaseUrl());
            HttpUrl.append(BINDUSER_URL);
            // 获取所有的
            HttpUrl.append("?unitid=0");
            mHttpRequest.setSid(sid);
            ireturn = mHttpRequest.doGet(HttpUrl.toString(), recive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(recive);
            } else
                ireturn = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ireturn;
    }
    
    /**91通行证身份绑定
     * @param authcode
     * @param receive
     * @return
     */
    public int userBind(String authcode, String sid, StringBuilder receive){
        int ireturn = 0;
        JSONObject json = new JSONObject();
        try {
            json.put("authcode", authcode);
            StringBuilder HttpUrl = new StringBuilder();
            HttpUrl.append(getBaseUrl()).append(USERBIND_URL);
            mHttpRequest.setSid(sid);
            ireturn = mHttpRequest.doPost(HttpUrl.toString(), json, receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ireturn;
    }
    
    /**取消身份绑定
     * @param unitid
     * @param oap_uid
     * @param receive
     * @return
     */
    public int userBindCancel(long unitid, long oap_uid, String sid, StringBuilder receive){
        int ireturn = 0;
        JSONObject json = new JSONObject();
        try {
            json.put("unitid", unitid);
            json.put("uid", oap_uid);
            StringBuilder HttpUrl = new StringBuilder();
            HttpUrl.append(getBaseUrl()).append(USERBINDCANCEL_URL);
            mHttpRequest.setSid(sid);
            ireturn = mHttpRequest.doPost(HttpUrl.toString(), json, receive);
            if (ireturn != HttpStatus.SC_OK) {
                _getResponseErrMsg(receive);
            } else
                ireturn = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ireturn;
    }

    /**
     * 解析错误信息
     * 
     * @param receive
     * @return
     */
    private void _getResponseErrMsg(StringBuilder receive) {

        if (receive != null &&
        	receive.length() > 0 && 
        	!(receive.toString()).equals("java.lang.NullPointerException")) {
            try {
                JSONObject json = new JSONObject(receive.toString());
                if (json.has("msg")) {
                    receive.delete(0, receive.length());
                    receive.append(json.getString("msg"));
                }
            } catch (Exception e) {
            }
        }
    }
    
    public int userLoginCookie( String cookie, String blowfish, long unitid, long uid,ClientInfo clientInfo,
            StringBuilder receive) {
    	return userLoginCookie(cookie, blowfish, unitid, uid, 0,clientInfo, receive);
    }

    public int userLoginCookie( String cookie, String blowfish, long unitid, long uid,int isedu,ClientInfo clientInfo,
            StringBuilder receive) {
        int ireturn = R.string.nd_oap_login_error;
        // 连接oap通讯
        JSONObject json = new JSONObject();
        try {
            json.put("cookie", cookie);
            json.put("appid", mAppid);
            json.put("blowfish", blowfish);
            if (unitid > 0) {
                json.put("unitid", unitid);
                json.put("uid", uid);
            }
            json.put("isedu", isedu);
            if (clientInfo!=null){
            	json.put("clientinfo", clientInfo.toJsonObject());
            }
            String HttpUrl = getBaseUrl();
            HttpUrl += LOGIN_URL_COOKIE;
            ireturn = mHttpRequest.doPost(HttpUrl, json, receive);
            if (ireturn != HttpStatus.SC_OK) {
                switch (ireturn) {
                case 430:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_cookie_430;
                    break;
                case 403:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_cookie_403;
                    break;
                case 405:
                    receive.delete(0, receive.length());
                    ireturn = R.string.nd_login_cookie_405_OAP;
                    break;
                default:
                    _getResponseErrMsg(receive);
                    break;
                }
            } else
                ireturn = 0;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            ireturn = R.string.nd_json_error;
        } finally {
            json = null;
        }
        return ireturn;
    }
    
    public int userLoginTicket( String ticket, String blowfish, long unitid, long uid,ClientInfo clientInfo,
    		StringBuilder receive) {
    	int ireturn = R.string.nd_oap_login_error;
    	// 连接oap通讯
    	JSONObject json = new JSONObject();
    	try {
    		json.put("ticket", ticket);
    		json.put("appid", mAppid);
    		json.put("blowfish", blowfish);
    		if (unitid > 0) {
    			json.put("unitid", unitid);
    			json.put("uid", uid);
    		}
    		if (clientInfo!=null){
    			json.put("clientinfo", clientInfo.toJsonObject());
    		}
    		String HttpUrl = getBaseUrl();
    		HttpUrl += LOGIN_URL_TICKET;
    		ireturn = mHttpRequest.doPost(HttpUrl, json, receive);
    		if (ireturn != HttpStatus.SC_OK) {
    			switch (ireturn) {
    			case 430:
    				receive.delete(0, receive.length());
    				ireturn = R.string.nd_login_cookie_430;
    				break;
    			case 403:
    				receive.delete(0, receive.length());
    				ireturn = R.string.nd_login_ticket_403;
    				break;
    			case 404:
    				receive.delete(0, receive.length());
    				ireturn = R.string.nd_login_ticket_404;
    				break;
    			default:
    				_getResponseErrMsg(receive);
    				break;
    			}
    		} else
    			ireturn = 0;
    	} catch (JSONException e) {
    		// TODO Auto-generated catch block
    		// e.printStackTrace();
    		ireturn = R.string.nd_json_error;
    	} finally {
    		json = null;
    	}
    	return ireturn;
    }
    
    
}
